﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Board1.Info;
using System.Net;
using System.Collections.ObjectModel;
using System.ComponentModel;
using Board1.Unleashed;
using System.Windows.Input;
using System.Threading;
using System.Windows;
using System.Text.RegularExpressions;
namespace Board1.GetData
{
    public class DataHot100 : INotifyPropertyChanged
    {
        // link cac bang xep hang
        string[] link = { "http://www.billboard.com/charts/hot-100",
                           "http://www.billboard.com/charts/hot-100?page=1", 
                           "http://www.billboard.com/charts/hot-100?page=2",
                           "http://www.billboard.com/charts/hot-100?page=3",
                        "http://www.billboard.com/charts/hot-100?page=4",
                        "http://www.billboard.com/charts/hot-100?page=5",
                        "http://www.billboard.com/charts/hot-100?page=6",
                        "http://www.billboard.com/charts/hot-100?page=7",
                        "http://www.billboard.com/charts/hot-100?page=8",
                        "http://www.billboard.com/charts/hot-100?page=9",};
        public DataHot100()
        {

            // bat su kien khi keo xuong day man hinh
           // getDataHot100(link[0]);
            fetchMoreDataCommand = new DelegateCommand(
                obj =>
                {
                    if (busy)
                    {
                        return;
                    }
                    Busy = true;
                    ThreadPool.QueueUserWorkItem(
                        delegate
                        {
                            Thread.Sleep(3000);
                            Deployment.Current.Dispatcher.BeginInvoke(
                                delegate
                                {
                                    if(_topHot100Song.Count<=100)
                                        AddMoreItems();
                                        Busy = false;
                                });
                        });

                });
        }
        //tai them noi dung
        private void AddMoreItems()
        {
            start = 0;
            content = null;
            int i = _topHot100Song.Count / 10;
            getDataHot100(link[i]);
        }

        private WebClient downloadURL = new WebClient();
        private string webData = null;
        private int start = 0, des1 = 0, des2 = 0;
        private MatchCollection content;

        private static ObservableCollection<HubTileItem> _hubList = new ObservableCollection<HubTileItem>();
        public static ObservableCollection<HubTileItem> HubList
        {
            get { return _hubList; }
        }

        private static ObservableCollection<SongData> _topHot100Song = new ObservableCollection<SongData>();
        public static  ObservableCollection<SongData> TopHot100Songs
        {
            get { return _topHot100Song; }
        }
        
        //tai noi dung trang html
        private void getDataHot100(string link)
        {
            //tai du lieu tu trang web
            try
            {
                downloadURL.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadStringCallback);
                downloadURL.DownloadStringAsync(new Uri(link));
            }
            catch (System.Exception)
            {
                MessageBox.Show("Internet Connection Error", "Error", MessageBoxButton.OK);
            }
        }

        private void DownloadStringCallback(object sender, DownloadStringCompletedEventArgs e)
        {
            if (!e.Cancelled && e.Error == null)
            {
                webData = (string)e.Result;
                htmlHandle1(webData);
                setListHubTile();
            }
            else
            {
                MessageBoxResult warning = MessageBox.Show("Error");
            }
            downloadURL.CancelAsync();
        }
        
        // xu li noi dung html de thu thap noi dung
        private void htmlHandle1(string webData)
        {
            while (start < webData.Length && des1 != -1)
            {
                SongData newItem = new SongData();
                des1 = webData.IndexOf("<article id=", start);
                if (des1 == -1) break;
                des2 = webData.IndexOf("</header>", des1);
                if (webData.Substring(des1, des2 - des1).Contains("song_review"))
                {
                    //lay ten bai hat
                    int songStart = webData.IndexOf("<h1>", des1);
                    int songEnd = webData.IndexOf("</h1>", songStart);
                    newItem.songName = webData.Substring(songStart + 4, songEnd - songStart - 4);

                    //lay vi tri
                    newItem.songPossition = (_topHot100Song.Count + 1).ToString();

                    //lay thong tin artist
                    int artistEnd;
                    des2 = webData.IndexOf("<br>", songEnd);
                    if (webData.Substring(des1, des2 - des1).Contains("<a href"))
                    {
                        int artistStart = webData.IndexOf("<a href", songEnd);
                        artistStart = webData.IndexOf(">", artistStart);
                        artistEnd = webData.IndexOf("</", artistStart);
                        newItem.artistName = webData.Substring(artistStart + 1, artistEnd - artistStart - 1);
                    }
                    else
                    {
                        int artistStart = webData.IndexOf("chart_info", songEnd);
                        artistStart = webData.IndexOf(">", artistStart);
                        artistEnd = webData.IndexOf("<br>", artistStart);
                        newItem.artistName = webData.Substring(artistStart + 8, artistEnd - artistStart - 20);
                    }
                    //lay thong tin album
                    int albumStart = webData.IndexOf("<br>", artistEnd);
                    int albumEnd = webData.IndexOf("</p>", albumStart);
                    newItem.albumName = webData.Substring(albumStart + 12, albumEnd - albumStart - 22);
                    if (newItem.albumName.Length == 0) newItem.albumName = "Single";

                    //lay image link
                    int imgStart = webData.IndexOf("<img", albumEnd);
                    imgStart = webData.IndexOf("src=", imgStart);
                    int imgEnd = webData.IndexOf("alt", imgStart);
                    string img = webData.Substring(imgStart + 5, imgEnd - imgStart - 7);
                    if (img.Contains("no-artist.png"))
                        img = "http://www.billboard.com/sites/all/themes/bb/images/default/no-artist.png";
                    newItem.imgSource = img;

                    _topHot100Song.Add(newItem);
                    start = des2 + 1;
                    //break;
                }
                else
                {
                    webData = null;
                    //start = 0;
                    break;
                }
            }
        }
        private void htmlHandle(string webData)
        {
            content = Regex.Matches(webData, "<article id=\"(.*?)\" class=\"song_review(.*?)\">(.*?)</article>", RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase);
            foreach (Match m in content)
            {
                SongData newItem = new SongData();
                // ten bai hat
                Match mSong = Regex.Match(m.Value, "<h1>(.*?)</h1>");
                string tSong = mSong.Groups[1].ToString();
                newItem.songName = tSong;

                // ten nghe si
                Match mArtist = Regex.Match(m.Value, "<a href=\"/artist(.*?)>(.*?)</a>");
                string tArtist = mArtist.Groups[2].ToString();
                newItem.artistName = tArtist;

                //ten album
                Match mAlbum = Regex.Match(m.Value, "<br>(.*?)</p>", RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase);
                string tAlbum = mAlbum.Groups[1].ToString();
                tAlbum = tAlbum.Replace("\r\n", "");
                tAlbum = tAlbum.Substring(6, tAlbum.Length - 16);
                if (tAlbum.Length == 0) tAlbum = "Single";
                newItem.albumName = tAlbum;

                //lay peak possition
                Match mPeak = Regex.Match(m.Value, "<i class=\"icon peak\"></i>(.*?)<span");
                string tPeak = mPeak.Groups[1].ToString();
                newItem.peak = tPeak;

                //lay last possition
                Match mLast = Regex.Match(m.Value, "<i class=\"icon shift\"></i>(.*?)<span");
                string tLast = mLast.Groups[1].ToString();
                if (tLast.Length == 0) tLast = "-";
                newItem.last = tLast;

                //lay week on chart
                Match mWeek = Regex.Match(m.Value, "<i class=\"icon duration\"></i>(.*?)<span");
                string tWeek = mWeek.Groups[1].ToString();
                newItem.week = tWeek;

                //lay Img
                Match mImg = Regex.Match(m.Value, "<img(.*?)src=(.*?)alt=");
                string tImg = mImg.Groups[2].ToString().Replace("\"", "");
                if (tImg.Contains("no-artist.png")) tImg = "http://www.billboard.com/sites/all/themes/bb/images/default/no-artist.png";
                newItem.imgSource = tImg;

                //lay possition
                newItem.songPossition = (_topHot100Song.Count + 1).ToString();
                //them vao list
                _topHot100Song.Add(newItem);
                if (Int16.Parse(newItem.songPossition) % 10 == 0) break;
            }
            webData = null;
        }

        //thiet lap cac noi dung cho HubTile
        private void setListHubTile()
        {
            for(int i = _hubList.Count; i< _topHot100Song.Count; i++)
            {
                HubTileItem newItem= new HubTileItem();
                SongData temp = _topHot100Song[i];
                newItem.uriSource= temp.imgSource;
                newItem.title= "by \""+ temp.artistName+"\"";
                newItem.message="NO "+temp.songPossition+" ."+"\""+temp.songName+"\"" +" from "+ "\""+ temp.albumName+"\""; 
                newItem.notification=temp.songPossition+" . "+ temp.songName;
                _hubList.Add(newItem);
            }
        }

        readonly DelegateCommand fetchMoreDataCommand;

        public ICommand FetchMoreDataCommand
        {
            get { return fetchMoreDataCommand; }
        }

        private bool busy;
        public bool Busy
        {
            get { return busy; }
            set 
            {
                if (busy == value)
                {
                    return;
                }
                busy = value;
                OnPropertyChanged(new PropertyChangedEventArgs("Busy"));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            var tempEvent = PropertyChanged;
            if (tempEvent != null)
            {
                tempEvent(this, e);
            }
        }
    }
}
